package com.ltedu.oss.storage.impl;

import cn.hutool.core.date.DateTime;
import com.ltedu.common.enums.ErrorCodeEnum;
import com.ltedu.common.exception.BaseException;
import com.ltedu.common.utils.UUIDUtils;
import com.ltedu.oss.storage.Storage;
import com.ltedu.oss.utils.FileKit;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @className: QiniuStorageImpl
 * @auther: Jerry
 * @date: 2020/11/26 13:35
 * @desctiption: 七牛云上传接口
 * @version: 1.0
 */
@Component
public class QiniuStorageImpl extends AbstractStorage implements Storage {

    @Value("${qiniu_oss_domain}")
    private String qiniuOssDomain;
    @Value("${qiniu_oss_key}")
    private String qiniuOssKey;
    @Value("${qiniu_oss_secret}")
    private String qiniuOssSecret;
    @Value("${qiniu_oss_bucket}")
    private String qiniuOssBucket;
    private Logger log = LoggerFactory.getLogger(QiniuStorageImpl.class);

    /**
     * 上传文件
     *
     * @param bytes           字节
     * @param pathAndFileName 路径和文件名
     * @return {@link String}* @throws Exception 异常
     */
    @Override
    public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
        String accessKey = qiniuOssKey;
        String secretKey = qiniuOssSecret;
        String domain = qiniuOssDomain;
        String bucket = qiniuOssBucket;

        if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
            throw new BaseException(ErrorCodeEnum.QINIU_CONFIG_ERROR);
        }

        String filePath = new DateTime().toString("yyyy/MM/dd");
        String path = filePath + "/" + UUIDUtils.generatorUUId() +  FileKit.getSuffix(pathAndFileName);

        Zone z = Zone.autoZone();
        Configuration configuration = new Configuration(z);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, path);

        UploadManager uploadManager = new UploadManager(configuration);
        Response response = uploadManager.put(bytes, path, upToken);

        if (!response.isOK()) {
            throw new BaseException(response.bodyString());
        }
        return domain.trim() + "/" + path;
    }

    /**
     * 删除文件
     *
     * @param storePath 存储路径
     */
    @Override
    public void deleteFile(String storePath) {
        String accessKey = qiniuOssKey;
        String secretKey = qiniuOssSecret;
        String domain = qiniuOssDomain;
        String bucket = qiniuOssBucket;

        if (StringUtils.isAnyBlank(accessKey, secretKey, domain, bucket)) {
            throw new BaseException(ErrorCodeEnum.QINIU_CONFIG_ERROR);
        }

        String path = StringUtils.remove(storePath, domain.trim());

        Zone z = Zone.autoZone();
        Configuration configuration = new Configuration(z);
        Auth auth = Auth.create(accessKey, secretKey);

        BucketManager bucketManager = new BucketManager(auth, configuration);
        try {
            bucketManager.delete(bucket, path);
        } catch (QiniuException e) {
            Response r = e.response;
            log.error(e.getMessage(), r.toString());
        }
    }
}
